package com.iflytek.cosmo.ocr.support.license.server.v1;

import java.net.SocketException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.iflytek.cosmo.ocr.common.utils.ComputerIdentifierExtractor;
import com.iflytek.cosmo.ocr.support.license.LicenseVersion;
import com.iflytek.cosmo.ocr.support.license.server.ServerLicense;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/6/29
 */
@Data
public class ServerLicenseV1 extends ServerLicense {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /** MAC分隔符 */
    protected static final String MAC_SEPARATOR = "/";

    /** 服务器MAC列表 */
    private List<String> macList;

    public ServerLicenseV1() {
        this.version = LicenseVersion.V1.getCode();
    }

    public ServerLicenseV1(String license) {
        super(license);
        String detail = license.substring(license.indexOf(SUBCLASS_SEPARATOR) + 1);
        this.macList = Arrays.asList(detail.split(MAC_SEPARATOR));
    }

    public boolean valid() {
        boolean superValid = super.valid();
        if (!superValid) {
            return false;
        }
        if (CollUtil.isEmpty(this.macList)) {
            logger.info("授权码中未包含MAC信息");
            return false;
        }

        // 读取本机MAC信息
        List<String> localMacList = null;
        try {
            localMacList = ComputerIdentifierExtractor.readMacList();
        }
        catch (Exception e) {
            logger.warn("读取本机MAC信息异常", e);
            return false;
        }

        if (CollUtil.isEmpty(localMacList)) {
            logger.info("无法取得到本机MAC信息");
            return false;
        }
        logger.info("本机MAC信息: " + String.join(", ", localMacList));

        return CollUtil.containsAny(macList, localMacList);
    }

    public static void main(String[] args) throws SocketException {
        List<String> macList = ComputerIdentifierExtractor.readMacList();
        System.out.println(macList);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString());

        // mac列表
        String macListStr = null;
        if (macList != null && !macList.isEmpty()) {
            macListStr = macList.stream().map(s -> StrUtil.removeAll(s, '-', ':')).map(String::toLowerCase).collect(
                    Collectors.joining(MAC_SEPARATOR));
        }
        sb.append(macListStr);

        return sb.toString();
    }
}
